<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/28
 * Time: 9:24
 */

namespace app\api\controller;

use think\Controller;
use think\Db;
use think\cache\driver\Redis;

header("ACCESS-CONTROL-ALLOW-ORIGIN:http://114.215.68.205");
class Home extends Controller{

    protected static $arr;

    public function _initialize(){

        parent::_initialize();
        //接收用户cookie信息
        if (isset($_COOKIE['appAndroid']) || isset($_COOKIE['appIOS'])) {
            $appinfo = isset($_COOKIE['appAndroid']) ? $_COOKIE['appAndroid'] : $_COOKIE['appIOS'];
            $cookieinfo = explode(',', $appinfo);
            cookie('username', trim($cookieinfo[0]));
            cookie('password', trim($cookieinfo[1]));
            cookie('login_key', trim($cookieinfo[3]));
            cookie('login_from', intval($cookieinfo[4]));
            if (isset($_COOKIE['appAndroid'])) {
                cookie('app_from', 1);
            } else {
                cookie('app_from', 2);
            }
        }

        $appfrom = cookie('app_from') ? cookie('app_from') : 0;
        $this->assign('appfrom', $appfrom);

        //验证加密
        $action = request()->action();
        if( 'youhui_detail'!=$action && 'winlist'!=$action && 'favourable'!=$action && 'popContainer'!=$action&& 'NoticeList'!=$action ){
            $VALUE_KEY = ['afewfewfew21342dsaewf'=>'8f4da4f9ew4f98ewq65fwe48f9w'];
            $HEADER_TIME = isset($_SERVER['HTTP_TIME']) ? $_SERVER['HTTP_TIME'] : '';
            $HEADER_KEY = isset($_SERVER['HTTP_KEY']) ? $_SERVER['HTTP_KEY'] : '';
            $HEADER_SIGN = isset($_SERVER['HTTP_SIGN']) ? $_SERVER['HTTP_SIGN'] : '';
            $POST_LOGIN_KEY = isset($_SERVER['HTTP_LOGINKEY']) ? $_SERVER['HTTP_LOGINKEY'] : ( isset($_POST['login_key']) ? $_POST['login_key'] : '' );
            $POST_NAME = isset($_SERVER['HTTP_USERNAME']) ? $_SERVER['HTTP_USERNAME'] : (isset($_POST['username']) ? $_POST['username'] : (isset($_POST['name']) ? $_POST['name']:''));
            if( !isset($VALUE_KEY[$HEADER_KEY]) ){
                exit(json_encode(['result'=>0], JSON_UNESCAPED_UNICODE));
            }
            $validation =  $HEADER_TIME.$VALUE_KEY[$HEADER_KEY].$POST_LOGIN_KEY.$POST_NAME;
            if( $HEADER_SIGN != md5($validation) ){
                exit(json_encode(['result'=>0], JSON_UNESCAPED_UNICODE));
            }
        }
    }
    /**
     * Android 购彩首页
     */
    public function index(){
        //手机广告
        $pc_guangg =  Db::name('sjgg')->where('gg_class<5')->select();
        //展示的彩种
        $rem_top= Db::name('caipai_list')->where('cp_if_open<2 and cp_mb_index=1')->order('cp_mb_px ASC')->select();
        $config = config("lotterys");
        foreach( $rem_top as &$v ){
            foreach($config as $k=>$val){
                in_array($v['id'],$val) && $v['abc'] = $k;
            }
        }
        unset($v);
        //滚动公告
        $hdlbtest = Db::name('xt_gonggao')->where(['is_roll'=>1,'suggest_mobile'=>1])->order('paixu','DESC')->select();

        $redis = new Redis();
        $reward_list = $redis->get('reward_list');
        if( empty($reward_list) ){
            $reward_list = db('touzhu_list_ok')->alias('tlo')
                ->field('tlo.username,tlo.zjje,cl.cp_name_old')
                ->join('__CAIPAI_LIST__ cl','cl.id=tlo.czid')
                ->join('__USERNAME__ u','u.username=tlo.username')
                ->where('u.swzh&u.nbzh','<>','1')
                ->where('tlo.zjje','>',0)
                ->order('tlo.tz_time','DESC')
                ->limit(30)
                ->select();
            $redis->set('reward_list',$reward_list,600);
        }
        //在线客服
        $zxkf = Db::name('xt_kflink')->where('type',4)->field('qq')->find();
        foreach($reward_list as &$v) {
        	$v['username'] = substr($v['username'],0,4);
        	$v['zjje'] = sprintf('%.2f',$v['zjje']);
        }
        unset($v);
        $ret = array(
            'result'=>1,
            'ResultMsg'=>'',
            'datas' => [
                'advert' => [],    //轮播图
                'lottery' => [],  //彩种
                'notice' => [],    //滚动广告
                'winning'=>[],		//最新中奖
                'customer'=>''		//在线客服
            ]
        );
        $ret['datas']['customer'] = $zxkf['qq'];
        foreach($pc_guangg as $v){
            $ret['datas']['advert'][] = array('img'=>$_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/static/attachment/'.$v['gg_img'],'url'=>$v['gg_url']);
        }
        foreach($rem_top as $v){
            $val = array('id'=>$v['id'],'img'=>$_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/'.$v['logo'],'remark'=>$v['remark']);
            $val['name'] = !empty($v['cp_name_new']) ? trim($v['cp_name_new']) : trim($v['cp_name_old']);
            $val['abc'] = $v['abc'];
            $ret['datas']['lottery'][] = $val;
        }
        foreach( $hdlbtest as $v){
            $ret['datas']['notice'][] = array('id'=>$v['id'],'title'=>$v['title']);
        }
        foreach ($reward_list as $v){
        	$ret['datas']['winning'][] = array('user'=>$v['username'],'zjje'=>$v['zjje'],'cp_name'=>$v['cp_name_old']);
        }
        echo json_encode($ret,JSON_UNESCAPED_UNICODE);
    }
    public function noticeList(){
        //滚动列表
        $list = Db::name('xt_gonggao')->where(['suggest_mobile'=>1,'xianshi'=>2])->order('paixu','DESC')->select();
        $this->assign('list',$list);
        return $this->fetch('notice_list');
    }
    //滚动消息详情
    public function noticeDetail(){

        $nid = input('get.nid') ? input('get.nid') : 0;
        $detail = array();
        if($nid > 0) {
            //公告详情信息
            $detail = Db::name('xt_gonggao')->where('id',$nid)->find();
        }
        $this->assign('detail',$detail);
        $this->assign('title','系统公告');
        return $this->fetch('notice_detail');
    }
    //首页中奖排行榜

    public function winList(){

        $reward_list = db('touzhu_list_ok')->alias('tlo')
            ->join('__CAIPAI_LIST__ cl','cl.id=tlo.czid')
            ->join('__USERNAME__ u','u.username=tlo.username')
            ->field('tlo.username,tlo.zjje,cl.cp_name_old,cl.cp_name_new')
            ->where('u.swzh&u.nbzh','<>','1')
            ->where('tlo.zjje','>',0)
            ->order('tlo.tz_time','DESC')
            ->limit(30)
            ->select();
        foreach($reward_list as &$v) {
            $v['zjje'] = sprintf('%.2f',$v['zjje']);
            $v['cp_name'] = !empty($v['cp_name_new']) ? $v['cp_name_new'] : $v['cp_name_old'];
            $v['username'] =  substr($v['username'],0,4);
        }
        unset($v);
        $this->assign('list',$reward_list);
        return  $this->fetch('win_list');
    }
    //全部彩种
    public function allLottery(){
        $list = Db::name('caipai_list')->where('cp_if_open<2')->order('cp_mb_px desc')->select();
        $data = array();
        foreach($list as $val){
            $data[] = array(
                'id' =>$val['id'],
                'logo' => $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/'.$val['logo'],
                'cp_name' => !empty($val['cp_name_new']) ? $val['cp_name_new'] : $val['cp_name_old']
            );
        }
        $ret = array(
            'result'=>1,
            'ResultMsg'=>'',
            'datas' => $data
        );
        echo json_encode($ret,JSON_UNESCAPED_UNICODE);
    }

    /**
     * 优惠活动
     * @return mixed
     */
    public function favourable(){
        $list = Db::name('xt_yhhd_list')->field('id,title,pic,begin_time,end_time')->where('xianshi',1)->order('paixu','DESC')->select();
        $this->assign('youhui_list',$list);
        return $this->fetch('youhui');
    }
    public function youhui_detail(){

        $id = input('id') ? input('id') : '';
        $info = Db::name('xt_yhhd_list')->where(['id'=>$id,'xianshi'=>1])->find();
        $this->assign('info',$info);
        return $this->fetch('youhui_detail');
    }
    /**
     * 配置信息
     */
    public function configuration(){
        $conf = Db::name('xt_reg')->find();

        $on_lay = Db::name('bonus_lay')->find();
        $hb = 0;
        if( 0!=intval($on_lay['flip']) && (strtotime($on_lay['start_time']) < time() && strtotime($on_lay['end_time']) > time()) ){
            $hb = 1;
        }
        $ret = array(
            'result'=>1,
            'ResultMsg'=>'',
            'datas' => array(
                'code' => empty($conf) ? 0 : intval($conf['codo_open']),
                'zcm' => empty($conf) ? 0 : intval($conf['tjr_open']),
                'hb' => $hb
            )
        );
        echo json_encode($ret,JSON_UNESCAPED_UNICODE);
    }
    public function popWindow(){
        $list = Db::name('xt_gonggao')->where(['suggest_mobile'=>1,'xianshi'=>1])->field('id,title,ggtext')->order('fatime desc')->select();
        $ret = array(
            'result'=>1,
            'ResultMsg'=>'',
            'datas' => [
                'num' => count($list),
                'title' => '',
                'content' => '',
                'list' => []
            ]
        );
        $titleAttr = [];
        foreach($list as $k=>$v){
            $titleAttr[] = ($k+1) .'.'. $v['title'];
            $ret['datas']['list'][] =  $v['title'];
        }
        $ret['datas']['title'] = implode(PHP_EOL,$titleAttr).PHP_EOL.PHP_EOL."点击查看详情";
        if( count($list) > 0 ) $ret['datas']['content'] = 'api/home/popContainer';
        echo json_encode($ret,JSON_UNESCAPED_UNICODE);
    }
    public function popContainer(){
        $list = Db::name('xt_gonggao')->where(['suggest_mobile'=>1,'xianshi'=>1])->field('id,title,ggtext')->order('fatime desc')->select();
        $this->assign('list',$list);
        return $this->fetch('container');
    }
    public function advert(){
        $files = self::findFile("uploads/advice");
        $row = array(
            'result'=>0,
            'ResultMsg'=>'暂无信息',
        );
        if( !empty($files) ){
            $row['result'] = 1;
            $row['ResultMsg'] = '有信息';
            foreach($files as $file){
                $row['datas'][] = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/'.$file;
            }
        }
        echo json_encode($row,JSON_UNESCAPED_UNICODE);
    }
    static function findFile($flodername){
        if (!is_dir($flodername)) {
            return array();
        }
        if ($fd = opendir($flodername)) {
            while($file = readdir($fd)) {
                if ($file != "." && $file != "..") {
                    $newPath = $flodername.'/'.$file;
                    if (is_dir($newPath)) {
                        self::findFile($newPath);
                    } else {
                        self::$arr[$file] = $newPath;
                    }
                }
            }
        } else {
            return array();
        }
        return self::$arr;
    }
    public function activity(){
        $duquhjud = Db::name('xt_zzhd')->where('ifopen','<',2)->select();
		$i = 0;
		$result='';
		$username=cookie('username');
		 foreach ($duquhjud as &$item){
            if ($item['tjzq'] == '1') {
                $year_now = date('Y-m-d', strtotime('-1 day')) . " 00:00:00";
                $year_now_1 = date('Y-m-d', strtotime('-1 day')) . " 23:59:59";
                $hdtime_1 = strtotime($year_now_1);
                $hdtime = strtotime($year_now);
                $taday = date('Y-m-d') . "00:00:00";
                $taday = strtotime($taday);
            }
            if ($item['tjzq'] == '2') {
                $year_now = date('Y-m-d', strtotime('-1 week last monday')) . "-01 00:00:00";
                $year_now_1 = date('Y-m-d', strtotime('last sunday')) . " 23:59:59";
                $hdtime_1 = strtotime($year_now_1);
                $hdtime = strtotime($year_now);
                $taday = date('Y-m-d', strtotime('sunday -6 day')) . " 00:00:00";
                $taday = strtotime($taday);
            }
            if ($item['tjzq'] == '3') {
                $year_now = date('Y-m', strtotime('-1 month')) . "-01 00:00:00";
                $year_now_1 = date('Y-m') . "-01 00:00:00";
                $hdtime_1 = strtotime($year_now_1);
                $hdtime = strtotime($year_now);
                $taday = date('Y-m') . "-01 00:00:00";
                $taday = strtotime($taday);
            }

			$item['tj_czje'] = explode('-', $item['tj_czje']);
			$item['tj_tzje'] = explode('-', $item['tj_tzje']);
			$item['hd_je'] = explode('-', $item['hd_je']);
			$item['tj_czje']=array_filter($item['tj_czje']);
			$item['tj_tzje']=array_filter($item['tj_tzje']);
			$item['hd_je']=array_filter($item['hd_je']);
			$i = count($item['hd_je']);
            $st=0;
			for($q=0;$q<$i;$q++){
				$item['sur'][]=[$item['tj_czje'][$q],$item['tj_tzje'][$q],$item['hd_je'][$q]];

			}
		

		 
            $czjes = Db::name('chongzhi_list')->where("username='{$username}' AND cztime>'{$hdtime}' AND cztime<'{$hdtime_1}' AND zt=1 ")->sum("je");
            $tzje=Db::name('touzhu_list_ok')->where("username='{$username}' AND tz_time>'{$hdtime}' AND tz_time<'{$hdtime_1}' ")->sum("tzje");
            $iflingq = Db::name('caijin_list')->where("username='{$username}' AND zzhdid='{$item["id"]}' AND fstime>='{$taday}' ")->find();
            if ($czjes < min($item['tj_czje']) || $tzje < min($item['tj_tzje']) || $iflingq['id'] > 0){
                $result=0;
            }else{
                 $result=1;
            }
            
            
            if($result==1){
                $item['sty']="#f0f";
                $item['islingqu']="可以领取";
            }else {
               $item['sty']="#999";
               $item['islingqu']="未达标，无法领取";
            }

            /*var_dump($item['tj_tzje']);*/
		} 
		unset($item);
		$this->assign('result',$result);
		$hdid = input('hdid')?input('hdid'):$duquhjud[0]['id'];
		$huodong = Db::name('xt_zzhd')->where('id',$hdid)->find();
		$this->assign('i',$i);
		$this->assign('rr',$huodong);
		$this->assign('query',$duquhjud);
		return $this->fetch();
    }
    public function level(){
        $row = array(
            'result'=>0,
            'ResultMsg'=>'暂无信息',
        );
        $list = Db::name("us_class")->order("czl asc")->select();
        if( !empty($list) ){
            $row['result'] = 1;
            $row['ResultMsg'] = '有信息';
            $row['datas'] = $list;
        }
        echo json_encode($row,JSON_UNESCAPED_UNICODE);
    }
}